<?php

/**
 * @author: chabonxu
 * @createTime: 2022/08/02 20:59
 * @company: https://www.moonton.com
 * @description: excel table
 */

require_once 'Sheet.php';
class Table
{
    private $sheets;

    protected function addSheet($name) {
        $sheet = new Sheet($name);
        $this->sheets[] = $sheet;
        return $sheet;
    }

    public function import($file) {
        $type = 'Excel2007';
        $xlsReader = PHPExcel_IOFactory::createReader($type);
        $sheets = $xlsReader->load($file);

        foreach ($sheets->getAllSheets() as $i => $objSheet) {
            if (isset($this->sheets[$i])) {
                $sheet = $this->sheets[$i];
                $sheet->setData($objSheet->toArray());
            }
        }
    }

    public function export($file, $bFile) {
        $objPHPExcel = new PHPExcel();
        foreach ($this->sheets as $index => $sheet) {
            $sheet->setSheetField($objPHPExcel, $index);
        }
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        if (!$bFile) {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename=' . $file);
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output');
        } else {
            $objWriter->save($file);
        }
    }

    public function exportData($file, $data, $bFile) {
        $objPHPExcel = new PHPExcel();
        foreach ($this->sheets as $index => $sheet) {
            $sheet->setSheetField($objPHPExcel, $index, $data[$index]);
            if (isset($data[$index])) {
                $sheet->setSheetData($objPHPExcel, $index, $data[$index]);
            }
        }

        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        if (!$bFile) {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename=' . $file);
            header('Cache-Control: max-age=0');

            $objWriter->save('php://output');
        } else {
            $objWriter->save($file);
        }
    }

    public function valid() {
        foreach ($this->sheets as $sheet) {
            if ($sheet->valid() == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        $data = array();
        foreach ($this->sheets as $sheet) {
            $data[] = $sheet->getData();
        }
        return $data;
    }

}